import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import { todoService } from '../services/todo'

export const useTodoStore = defineStore('todo', () => {
  const todos = ref([])
  const categories = ref([])
  const tags = ref([])
  const isLoading = ref(false)
  const error = ref(null)
  
  const completedTodos = computed(() => 
    todos.value.filter(todo => todo.completed)
  )
  
  const completionRate = computed(() => 
    todos.value.length ? 
    (completedTodos.value.length / todos.value.length) * 100 : 0
  )
  
  const todosByCategory = computed(() => {
    const result = {}
    categories.value.forEach(category => {
      result[category.id] = todos.value.filter(todo => 
        todo.category && todo.category.id === category.id
      )
    })
    return result
  })
  
  async function fetchTodos(params = {}) {
    isLoading.value = true
    error.value = null
    try {
      const response = await todoService.getTasks(params)
      console.log('获取任务响应:', response)
      
      if (response && response.code === 0) {
        // 修改这里，直接使用 response.data 作为任务列表
        todos.value = response.data || []
        console.log('设置任务列表:', todos.value)
      } else {
        console.error('获取任务响应格式不正确:', response)
      }
    } catch (err) {
      error.value = '获取待办事项失败'
      console.error('获取任务错误:', err)
    } finally {
      isLoading.value = false
    }
  }
  
  async function fetchCategories() {
    try {
      const response = await todoService.getCategories()
      console.log('获取分类响应:', response)
      
      if (response && response.code === 0) {
        categories.value = response.data || []
        console.log('设置分类列表:', categories.value)
      } else {
        console.error('获取分类响应格式不正确:', response)
      }
    } catch (err) {
      console.error('获取分类失败:', err)
    }
  }
  
  async function fetchTags() {
    try {
      const response = await todoService.getTags()
      console.log('获取标签响应:', response)
      
      if (response && response.code === 0) {
        tags.value = response.data || []
        console.log('设置标签列表:', tags.value)
      } else {
        console.error('获取标签响应格式不正确:', response)
      }
    } catch (err) {
      console.error('获取标签失败:', err)
    }
  }
  
  async function addTodo(todo) {
    try {
      const response = await todoService.createTask(todo)
      console.log('添加任务响应:', response)
      
      if (response && response.code === 0 && response.data) {
        todos.value.push(response.data)
        return response.data
      }
      return null
    } catch (err) {
      error.value = '添加待办事项失败'
      console.error('添加任务错误:', err)
      return null
    }
  }
  
  async function updateTodo(id, updates) {
    try {
      const response = await todoService.updateTask(id, updates)
      if (response && response.data) {
        const index = todos.value.findIndex(t => t.id === id)
        if (index !== -1) {
          todos.value[index] = response.data
        }
        return response.data
      }
      return null
    } catch (err) {
      error.value = '更新待办事项失败'
      console.error(err)
      return null
    }
  }
  
  async function deleteTodo(id) {
    try {
      await todoService.deleteTask(id)
      todos.value = todos.value.filter(t => t.id !== id)
      return true
    } catch (err) {
      error.value = '删除待办事项失败'
      console.error(err)
      return false
    }
  }
  
  async function batchUpdateTodos(ids, completed) {
    try {
      const response = await todoService.batchUpdateTasks(ids, completed)
      if (response && response.data) {
        // 更新本地状态
        ids.forEach(id => {
          const index = todos.value.findIndex(t => t.id === id)
          if (index !== -1) {
            todos.value[index].completed = completed
          }
        })
        return true
      }
      return false
    } catch (err) {
      error.value = '批量更新待办事项失败'
      console.error(err)
      return false
    }
  }
  
  async function addCategory(category) {
    try {
      const response = await todoService.createCategory(category)
      if (response && response.data) {
        categories.value.push(response.data)
        return response.data
      }
      return null
    } catch (err) {
      console.error('添加分类失败:', err)
      return null
    }
  }
  
  async function updateCategory(id, updates) {
    try {
      const response = await todoService.updateCategory(id, updates)
      if (response && response.data) {
        const index = categories.value.findIndex(c => c.id === id)
        if (index !== -1) {
          categories.value[index] = response.data
        }
        return response.data
      }
      return null
    } catch (err) {
      console.error('更新分类失败:', err)
      return null
    }
  }
  
  async function deleteCategory(id) {
    try {
      await todoService.deleteCategory(id)
      categories.value = categories.value.filter(c => c.id !== id)
      return true
    } catch (err) {
      console.error('删除分类失败:', err)
      return false
    }
  }
  
  async function addTag(tag) {
    try {
      const response = await todoService.createTag(tag)
      if (response && response.data) {
        tags.value.push(response.data)
        return response.data
      }
      return null
    } catch (err) {
      console.error('添加标签失败:', err)
      return null
    }
  }
  
  async function updateTag(id, updates) {
    try {
      const response = await todoService.updateTag(id, updates)
      if (response && response.data) {
        const index = tags.value.findIndex(t => t.id === id)
        if (index !== -1) {
          tags.value[index] = response.data
        }
        return response.data
      }
      return null
    } catch (err) {
      console.error('更新标签失败:', err)
      return null
    }
  }
  
  async function deleteTag(id) {
    try {
      await todoService.deleteTag(id)
      tags.value = tags.value.filter(t => t.id !== id)
      return true
    } catch (err) {
      console.error('删除标签失败:', err)
      return false
    }
  }
  
  async function getTaskStatistics(params = {}) {
    try {
      const response = await todoService.getTaskStatistics(params)
      return response
    } catch (err) {
      console.error('获取任务统计数据失败:', err)
      return null
    }
  }
  
  async function getProductivityTrend(params = {}) {
    try {
      const response = await todoService.getProductivityTrend(params)
      return response
    } catch (err) {
      console.error('获取生产力趋势数据失败:', err)
      return null
    }
  }
  
  async function getCategoryDistribution(params = {}) {
    try {
      const response = await todoService.getCategoryDistribution(params)
      return response
    } catch (err) {
      console.error('获取分类分布数据失败:', err)
      return null
    }
  }
  
  return {
    todos,
    categories,
    tags,
    isLoading,
    error,
    completedTodos,
    completionRate,
    todosByCategory,
    fetchTodos,
    fetchCategories,
    fetchTags,
    addTodo,
    updateTodo,
    deleteTodo,
    batchUpdateTodos,
    addCategory,
    updateCategory,
    deleteCategory,
    addTag,
    updateTag,
    deleteTag,
    getTaskStatistics,
    getProductivityTrend,
    getCategoryDistribution
  }
})